package com.example.shop.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.shop.common.api.ResponseResult;
import com.example.shop.common.api.ServiceReturn;
import com.example.shop.common.api.ServiceStateCode;
import com.example.shop.common.util.CachedThreadPoolUtil;
import com.example.shop.common.util.FileOptionUtil;
import com.example.shop.es.service.ElasticSearchClient;
import com.example.shop.goods.dao.GoodsStyleDao;
import com.example.shop.goods.dao.MerchantGoodsDetailBrowseInfoDao;
import com.example.shop.goods.dao.ModifyGoodBaseInfoParamDao;
import com.example.shop.goods.dto.*;
import com.example.shop.goods.service.GoodsService;
import com.example.shop.mapper.GoodsClassMapper;
import com.example.shop.mapper.GoodsDescriptionPictureMapper;
import com.example.shop.mapper.GoodsDetailsPictureMapper;
import com.example.shop.mapper.GoodsMapper;
import com.example.shop.pojo.*;
import com.example.shop.redis.enums.RedisKey;
import com.example.shop.redis.service.LettuceClient;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;


@Service
public class GoodsServiceImpl implements GoodsService {

    private final GoodsMapper goodsMapper;
    private final ModifyGoodBaseInfoParamDao modifyGoodBaseInfoParamDao;
    private final GoodsDescriptionPictureMapper descriptionPictureMapper;
    private final GoodsDetailsPictureMapper detailsPictureMapper;
    private final GoodsClassMapper goodsClassMapper;
    private final GoodsStyleDao goodsStyleDao;
    private final ElasticSearchClient esClient;
    private final LettuceClient redisClient;

    public GoodsServiceImpl(GoodsMapper goodsMapper, ModifyGoodBaseInfoParamDao modifyGoodBaseInfoParamDao, GoodsDescriptionPictureMapper descriptionPictureMapper, GoodsDetailsPictureMapper detailsPictureMapper, GoodsClassMapper goodsClassMapper, GoodsStyleDao goodsStyleDao, ElasticSearchClient esClient, LettuceClient redisClient) {
        this.goodsMapper = goodsMapper;
        this.modifyGoodBaseInfoParamDao = modifyGoodBaseInfoParamDao;
        this.descriptionPictureMapper = descriptionPictureMapper;
        this.detailsPictureMapper = detailsPictureMapper;
        this.goodsClassMapper = goodsClassMapper;
        this.goodsStyleDao = goodsStyleDao;
        this.esClient = esClient;
        this.redisClient = redisClient;
    }


    @Override
    public ServiceReturn<Boolean> deleteGoods(Merchant merchant, long goodsId) {
        int deleteRow = goodsMapper.deleteAllInfoAboutGoods(goodsId);
        if(deleteRow!=0){
            String deleteDir = Merchant.RESOURCE_ROOT_DIR + merchant.getMerchantAccount() + Merchant.GOODS_DIR + goodsId ;
            CachedThreadPoolUtil.submit(()->{
                try {
                    FileOptionUtil.deleteDir(deleteDir,true);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                esClient.deleteDocument(new GoodsDetailBrowseInfo(goodsId));
            });
            return new ServiceReturn<>(ServiceStateCode.SUCCESS,true);
        }
        return new ServiceReturn<>(ServiceStateCode.NO_SUCH_RECORD,false);
    }

    @Transactional
    @Override
    public ServiceReturn<MerchantGoodsDetailBrowseInfo> saveGoods(Merchant merchant,NewGoodsInfoParam newGoodsInfo) {

        Goods goods = newGoodsInfo.toGoods(merchant);
        String saveDir = Merchant.RESOURCE_ROOT_DIR + merchant.getMerchantAccount() + Merchant.GOODS_DIR + goods.getGoodsId() + File.separator;
        String videoSavePath = saveDir + "video.mp4";
        goods.setGoodsVideo(videoSavePath);
        try {
            FileOptionUtil.asyncWrite(videoSavePath,newGoodsInfo.getGoodsVideo().getBytes());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Goods模块里的GoodsServiceImpl的saveGoods保存视频出错");
        }
        //保存到商品表中
        int changeRow = goodsMapper.insert(goods);


        List<MultipartFile> descriptionPictureList = newGoodsInfo.getGoodsDescriptionPicture();
        List<String> descriptionPicturesRes = new ArrayList<>();

        //将描述图片保存到该商家的该商品的资源目录下
        for(int i=0;i<descriptionPictureList.size();i++){
            String descPictureSavePath = saveDir + "describe_" + System.currentTimeMillis() + i + ".png";
            descriptionPicturesRes.add(descPictureSavePath);
            try {
                FileOptionUtil.asyncWrite(descPictureSavePath,descriptionPictureList.get(i).getBytes());
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("Goods模块里的GoodsServiceImpl的saveGoods保存图片出错");
            }
        }
        //保存到商品的描述图片表中
        int changeRow2 = descriptionPictureMapper.insertList(goods.getGoodsId(), descriptionPicturesRes);


        //保存到商品的详细图片表中
        List<MultipartFile> detailsPictureList = newGoodsInfo.getGoodsDetailsPicture();
        List<String> detailsPicturesRes = new ArrayList<>();
        for(int i=0;i<detailsPictureList.size();i++){
            String detailSavePath = saveDir + "detail_"+ System.currentTimeMillis() + i + ".png";
            detailsPicturesRes.add(detailSavePath);
            try {
                FileOptionUtil.asyncWrite(detailSavePath,detailsPictureList.get(i).getBytes());
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("Goods模块里的GoodsServiceImpl的saveGoods保存图片出错");
            }
        }
        int changeRow3 = detailsPictureMapper.insertList(goods.getGoodsId(), detailsPicturesRes);


        //保存到商品的款式表中
        List<GoodsStyleParam> styleList = newGoodsInfo.getGoodsStyleList();
        List<GoodsClass> goodsClassList = new ArrayList<>();
        List<GoodsStyle> goodsStyleList = new ArrayList<>();
        for(int i=0;i<styleList.size();i++){
            GoodsClass goodsClass = styleList.get(i).toGoodsClass();
            goodsClass.setGoodsId(goods.getGoodsId());
            String stylePictureSavePath = saveDir + goodsClass.getGoodsClass() + ".png";
            goodsClass.setGoodsClassPicture(stylePictureSavePath);
            //将款式图片保存到对应的位置
            try {
                FileOptionUtil.asyncWrite(stylePictureSavePath,styleList.get(i).getClassPicture().getBytes());
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("Goods模块里的GoodsServiceImpl的saveGoods保存图片出错");
            }
            goodsClassList.add(goodsClass);
            goodsStyleList.add(GoodsStyle.getGoodsStyle(goodsClass));
        }
        int changeRow4 = goodsClassMapper.insertList(goodsClassList);
        //返回该商品的详细信息
        GoodsDetailBrowseInfo detailBrowseInfo = new GoodsDetailBrowseInfo();
        detailBrowseInfo.assignment(goods, descriptionPicturesRes, detailsPicturesRes,goodsStyleList,null);
        //异步将数据添加到es服务器中
        CachedThreadPoolUtil.submit(()->esClient.saveDocument(detailBrowseInfo, WriteRequest.RefreshPolicy.IMMEDIATE));
        MerchantGoodsDetailBrowseInfo merchantGoodsDetailBrowseInfo = new MerchantGoodsDetailBrowseInfo();
        merchantGoodsDetailBrowseInfo.assignment(goods, descriptionPicturesRes, detailsPicturesRes,goodsStyleList);
        return new ServiceReturn<>(ServiceStateCode.SUCCESS,merchantGoodsDetailBrowseInfo);
    }

    @Transactional
    @Override
    public ServiceReturn<Boolean> modifyGoodsBaseInfo(Merchant merchant,ModifyGoodBaseInfoParam modifyBaseInfo) {
        int updateRow = modifyGoodBaseInfoParamDao.updateNotNull(merchant.getMerchantId(),modifyBaseInfo);
        if(updateRow!=0){
            //同步到es中
            CachedThreadPoolUtil.submit(()->{
                GoodsDetailBrowseInfo updateInfo = new GoodsDetailBrowseInfo(modifyBaseInfo.getGoodsId());
                if(modifyBaseInfo.getGoodsName()!=null){
                    updateInfo.setGoodsName(modifyBaseInfo.getGoodsName());
                }
                if(modifyBaseInfo.getGoodsIntroduction()!=null){
                    updateInfo.setGoodsIntroduction(modifyBaseInfo.getGoodsIntroduction());
                }
                if(modifyBaseInfo.getGoodsType()!=null){
                    updateInfo.setGoodsType(modifyBaseInfo.getGoodsType());
                }
                esClient.updateDocument(updateInfo);
            });
            return new ServiceReturn<>(ServiceStateCode.SUCCESS,true);
        }
        return new ServiceReturn<>(ServiceStateCode.NO_SUCH_RECORD,false);
    }

    @Transactional
    @Override
    public ServiceReturn<GoodsStyle> addGoodsStyle(Merchant merchant, NewGoodsStyle newStyle) {
        GoodsStyleParam style = newStyle.getGoodsStyle();
        Long goodsId = newStyle.getGoodsId();
        String newGoodsClass = style.getGoodsClass();
        QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
        goodsQueryWrapper.eq("goods_id",goodsId);
        boolean goodsExist = goodsMapper.exists(goodsQueryWrapper);
        if(!goodsExist){
            return new ServiceReturn<>(ServiceStateCode.NOT_EXIST_GOODS,null);
        }
        QueryWrapper<GoodsClass> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id",goodsId);
        queryWrapper.eq("goods_class",newGoodsClass);
        boolean exists = goodsClassMapper.exists(queryWrapper);
        //判断新插入的款式是否已经存在
        if(!exists){
            GoodsClass goodsClass = style.toGoodsClass();
            goodsClass.setGoodsId(goodsId);
            GoodsStyle goodsStyle = style.toGoodsStyle();
            String saveDir = Merchant.RESOURCE_ROOT_DIR + merchant.getMerchantAccount() + Merchant.GOODS_DIR + newStyle.getGoodsId() + File.separator;
            String saveStylePicturePath = saveDir + goodsClass.getGoodsClass() + ".png";
            //设置款式的图片的保存路径
            goodsClass.setGoodsClassPicture(saveStylePicturePath);
            goodsStyle.setClassPicture(saveStylePicturePath);

            //插入到数据库中
            int changeRow = goodsClassMapper.insert(goodsClass);
            if(changeRow!=0){
                //异步保存到es和redis中
                CachedThreadPoolUtil.submit(()->{
                    //异步将数据保存起来
                    try {
                        FileOptionUtil.write(saveStylePicturePath,style.getClassPicture().getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String esScript =
                            "if(ctx._source['goodsStyleList'] == null){" +
                                "ctx._source['goodsStyleList'] = [];" +
                            "}" +
                            "ctx._source['goodsStyleList'].add(params.newStyle);";
                    HashMap<String, Object> params = new HashMap<>();
                    params.put("newStyle",goodsStyle);
                    GoodsDetailBrowseInfo detailBrowseInfo = new GoodsDetailBrowseInfo(newStyle.getGoodsId());
                    esClient.updateDocument(detailBrowseInfo,esScript,params);


                    //将添加的商品款式添加到redis中
                    String scriptStr =
                            "local exist = redis.call('EXISTS',KEYS[1]);" +
                            "local field = string.sub(ARGV[1],2,string.len(ARGV[1])-1);" +
                            "if exist == 1 then " +
                                "redis.call('HSET',KEYS[1],field,ARGV[2]);" +
                            "end" +
                            "return exist;";
                    DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>(scriptStr,Boolean.class);
                    redisClient.execLua(redisScript, Arrays.asList(RedisKey.HashMap.GOODS_INVENTORY.getKey() + goodsId),newGoodsClass,goodsClass.getClassInventory());

                });
                return new ServiceReturn<>(ServiceStateCode.SUCCESS,goodsStyle);
            }
            return new ServiceReturn<>(ServiceStateCode.FAILURE,null);
        }
        return new ServiceReturn<>(ServiceStateCode.STYLE_ALREADY_EXIST,null);
    }

    @Transactional
    @Override
    public ServiceReturn<GoodsStyle> modifyGoodsStyle(Merchant merchant,ModifyGoodsStyleParam modifyStyle) {
        Long goodsId = modifyStyle.getGoodsId();
        String beforeGoodsClass = modifyStyle.getModifyStyle().getGoodsClass();
        QueryWrapper<GoodsClass> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id",goodsId);
        queryWrapper.eq("goods_class",beforeGoodsClass);
        boolean exists = goodsClassMapper.exists(queryWrapper);
        if(exists){
            return new ServiceReturn<>(ServiceStateCode.STYLE_ALREADY_EXIST,null);
        }
        String saveDir = Merchant.RESOURCE_ROOT_DIR + merchant.getMerchantAccount() + Merchant.GOODS_DIR + goodsId + File.separator;
        //要修改的商品款式
        GoodsStyleParam styleParam = modifyStyle.getModifyStyle();
        String nowGoodsClass = styleParam.getGoodsClass();
        //如果要修改该款式的名,则要将之前的图片名修改为当前的名
        String beforePicturePath = saveDir+modifyStyle.getBeforeClass()+".png";
        String newStylePicturePath = beforePicturePath;
        if(nowGoodsClass!=null){
            newStylePicturePath = saveDir+nowGoodsClass+".png";
            //将该款式原本的图片的名字修改为，款式的新名
            FileOptionUtil.rename(beforePicturePath,newStylePicturePath);
        }
        //响应出去的款式对象
        GoodsStyle style = styleParam.toGoodsStyle();
        //写入数据库的款式对象
        GoodsClass goodsClass = styleParam.toGoodsClass();
        goodsClass.setGoodsId(goodsId);
        //如果要修改图片，则将图片写入新的路径
        if(styleParam.getClassPicture()!=null){
            goodsClass.setGoodsClassPicture(newStylePicturePath);
            style.setClassPicture(newStylePicturePath);
            try {
                FileOptionUtil.asyncWrite(newStylePicturePath,styleParam.getClassPicture().getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        int updateRow = goodsStyleDao.updateNotNull(merchant.getMerchantId(), modifyStyle.getBeforeClass(),goodsClass);
        if(updateRow!=0){
            //同步到es和redis中
            CachedThreadPoolUtil.submit(()->{
                String script =
                        "if(ctx._source['goodsStyleList'] != null){"+
                            "for(int i=0 ; i<ctx._source['goodsStyleList'].length ;i++){"+
                                "def style = ctx._source['goodsStyleList'][i];"+
                                "if(style.goodsClass == params.beforeClass){"+
                                    "def modifyStyle = params.modifyStyle;"+
                                    "if(modifyStyle.classPicture!= null){"+
                                        "style.classPicture = modifyStyle.classPicture;"+
                                    "}"+
                                    "if(modifyStyle.goodsClass!= null){"+
                                        "style.goodsClass = modifyStyle.goodsClass;"+
                                    "}"+
                                    "if(modifyStyle.classPrice != null){"+
                                        "style.classPrice = modifyStyle.classPrice;"+
                                    "}"+
                                    "if(modifyStyle.classInventory != null){"+
                                        "style.classInventory = modifyStyle.classInventory;"+
                                    "}" +
                                    "break;"+
                                "}"+
                            "}"+
                        "}";
                HashMap<String, Object> params = new HashMap<>();
                params.put("beforeClass",modifyStyle.getBeforeClass());
                params.put("modifyStyle",style);
                GoodsDetailBrowseInfo detailBrowseInfo = new GoodsDetailBrowseInfo(goodsId);
                //如果不存在该文档记录，则会报错，但是这个错误是可以接收的
                esClient.updateDocument(detailBrowseInfo,script,params);

                //将redis中该商品的该款式的库存进行修改
                String scriptStr =
                        "local exist = redis.call('EXISTS',KEYS[1]);" +
                        "local beforeField = string.sub(ARGV[1],2,string.len(ARGV[1])-1);" +
                        "local nowField = string.sub(ARGV[2],2,string.len(ARGV[2])-1);" +
                        "if exist == 1 then " +
                            "redis.call('HDEL',KEYS[1],beforeField)" +
                            "redis.call('HSET',KEYS[1],nowField,ARGV[2]);" +
                        "end" +
                        "return exist;";
                DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>(scriptStr,Boolean.class);
                redisClient.execLua(redisScript, Arrays.asList(RedisKey.HashMap.GOODS_INVENTORY.getKey() + goodsId),beforeGoodsClass,nowGoodsClass,goodsClass.getClassInventory());
            });
            return new ServiceReturn<>(ServiceStateCode.SUCCESS,style);
        }
        return new ServiceReturn<>(ServiceStateCode.NO_SUCH_RECORD,null);
    }

    @Transactional
    @Override
    public ServiceReturn<Boolean> deleteGoodsStyle(Merchant merchant,long goodsId, String goodsClass) {
        QueryWrapper<GoodsClass> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id",goodsId);
        Long count = goodsClassMapper.selectCount(queryWrapper);
        if(count<1){
            //说明该商品根本不存在，因为款式至少有1个
            return new ServiceReturn<>(ServiceStateCode.NOT_EXIST_GOODS,false);
        }
        else if(count==1){
            //要删除的商品的款式要至少保留一个1个款式，而不能全删除
            return new ServiceReturn<>(ServiceStateCode.CANT_WITHOUT_GOODS_CLASS,false);
        }
        int deleteRow = goodsClassMapper.delete(merchant.getMerchantId(),goodsId,goodsClass);
        if(deleteRow!=0){
            //同步到es和redis中
            CachedThreadPoolUtil.submit(()->{
                String saveDir = Merchant.RESOURCE_ROOT_DIR + merchant.getMerchantAccount() + Merchant.GOODS_DIR + goodsId + File.separator;
                FileOptionUtil.asyncDeleteFile(saveDir+goodsClass+".png");
                String script =
                        "if(ctx._source['goodsStyleList'] != null){" +
                            "for(int i=0 ; i<ctx._source['goodsStyleList'].length ;i++){" +
                                "def styleList = ctx._source['goodsStyleList'];" +
                                "if(styleList[i].goodsClass == params.deleteClass){" +
                                    "styleList.remove(i);" +
                                    "break;" +
                                "}"+
                            "}"+
                        "}";
                HashMap<String, Object> params = new HashMap<>();
                params.put("deleteClass",goodsClass);
                GoodsDetailBrowseInfo detailBrowseInfo = new GoodsDetailBrowseInfo(goodsId);
                //如果不存在该文档记录，则会报错，但是这个错误是可以接收的
                esClient.updateDocument(detailBrowseInfo,script,params);


                //将redis中该商品的该款式进行删除
                String scriptStr =
                        "local exist = redis.call('EXISTS',KEYS[1]);" +
                        "local field = string.sub(ARGV[1],2,string.len(ARGV[1])-1);" +
                        "if exist == 1 then " +
                            "redis.call('HDEL',KEYS[1],field)" +
                        "end" +
                        "return exist;";
                DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>(scriptStr,Boolean.class);
                redisClient.execLua(redisScript, Arrays.asList(RedisKey.HashMap.GOODS_INVENTORY.getKey() + goodsId),goodsClass);

            });
            return new ServiceReturn<>(ServiceStateCode.SUCCESS,true);
        }
        return new ServiceReturn<>(ServiceStateCode.NO_SUCH_RECORD,false);
    }

    @Transactional
    @Override
    public ServiceReturn<List<String>> addDescribePicture(Merchant merchant, long goodsId, List<MultipartFile> describePictureList) {
        QueryWrapper<Goods> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("goods_id",goodsId);
        boolean exists = goodsMapper.exists(queryWrapper1);
        //查看是否存在该商品
        if(!exists){
            return new ServiceReturn<>(ServiceStateCode.NOT_EXIST_GOODS,null);
        }
        //检测该商品的图片数目是否已经达到界限
        QueryWrapper<GoodsDescriptionPicture> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id",goodsId);
        Long describePictureCount = descriptionPictureMapper.selectCount(queryWrapper);
        if(describePictureCount+describePictureList.size()>GoodsDescriptionPicture.goodsDescribePictureMaxNum){
            return new ServiceReturn<>(ServiceStateCode.MORE_THAN_RATED_VALUE,null);
        }
        //图片的保存目录
        String saveDir = Merchant.RESOURCE_ROOT_DIR + merchant.getMerchantAccount() + Merchant.GOODS_DIR + goodsId + File.separator;
        ArrayList<String> viewPath = new ArrayList<>();
        ArrayList<String> savePathList = new ArrayList<>();
        for(int i=0;i<describePictureList.size();i++){
            String savePicturePath = saveDir + "describe_" + System.currentTimeMillis() + i + ".png";
            viewPath.add(ResponseResult.toRequestPath(savePicturePath));
            savePathList.add(savePicturePath);
        }
        //插入到数据库库中
        int changeRow = descriptionPictureMapper.insertList(goodsId,savePathList);
        //如果插入成功
        if(changeRow!=0){
            CachedThreadPoolUtil.submit(()->{
                //异步将图片保存起来
                for(int i=0;i<savePathList.size();i++){
                    MultipartFile pictureData = describePictureList.get(i);
                    //将所有的图片保存到指定位置
                    try {
                        FileOptionUtil.write(savePathList.get(i),pictureData.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //异步同步到es中
                String script =
                        "if(ctx._source['goodsDescriptionPicture'] == null){" +
                                "ctx._source['goodsDescriptionPicture'] = [];" +
                        "}" +
                        "ctx._source['goodsDescriptionPicture'].addAll(params.describePictureList);";
                HashMap<String, Object> params = new HashMap<>();
                params.put("describePictureList",viewPath);
                GoodsDetailBrowseInfo detailBrowseInfo = new GoodsDetailBrowseInfo(goodsId);
                //如果不存在该文档记录，则会报错，但是这个错误是可以接收的
                esClient.updateDocument(detailBrowseInfo,script,params);
            });
        }
        return new ServiceReturn<>(ServiceStateCode.SUCCESS,viewPath);
    }


    @Transactional
    @Override
    public ServiceReturn<List<String>> addDetailPicture(Merchant merchant, long goodsId, List<MultipartFile> detailPictureList) {
        QueryWrapper<Goods> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("goods_id",goodsId);
        boolean exists = goodsMapper.exists(queryWrapper1);
        if(!exists){
            return new ServiceReturn<>(ServiceStateCode.NOT_EXIST_GOODS,null);
        }
        //检测该商品的图片数目是否已经达到界限
        QueryWrapper<GoodsDetailsPicture> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id",goodsId);
        long describePictureCount = detailsPictureMapper.selectCount(queryWrapper);
        if(describePictureCount+detailPictureList.size()>GoodsDescriptionPicture.goodsDetailPictureMaxNum){
            return new ServiceReturn<>(ServiceStateCode.MORE_THAN_RATED_VALUE,null);
        }
        //图片的保存目录
        String saveDir = Merchant.RESOURCE_ROOT_DIR + merchant.getMerchantAccount() + Merchant.GOODS_DIR + goodsId + File.separator;

        ArrayList<String> viewPath = new ArrayList<>();
        ArrayList<String> savePathList = new ArrayList<>();

        for(int i=0;i<detailPictureList.size();i++){
            String savePicturePath = saveDir + "detail_" + System.currentTimeMillis() + i + ".png";
            viewPath.add(ResponseResult.toRequestPath(savePicturePath));
            savePathList.add(savePicturePath);
        }
        //插入到数据库库中
        int changeRow = detailsPictureMapper.insertList(goodsId,savePathList);
        //如果插入成功
        if(changeRow!=0){
            CachedThreadPoolUtil.submit(()->{
                //异步将图片保存起来
                for(int i=0;i<savePathList.size();i++){
                    MultipartFile pictureData = detailPictureList.get(i);
                    //将所有的图片保存到指定位置
                    try {
                        FileOptionUtil.write(savePathList.get(i),pictureData.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //异步同步到es中
                String script =
                        "if(ctx._source['goodsDetailsPicture'] == null){" +
                                "ctx._source['goodsDetailsPicture'] = [];" +
                        "}" +
                        "ctx._source['goodsDetailsPicture'].addAll(params.detailPictureList);";
                HashMap<String, Object> params = new HashMap<>();
                params.put("detailPictureList",viewPath);
                GoodsDetailBrowseInfo detailBrowseInfo = new GoodsDetailBrowseInfo(goodsId);
                //如果不存在该文档记录，则会报错，但是这个错误是可以接收的
                esClient.updateDocument(detailBrowseInfo,script,params);
            });
        }
        return new ServiceReturn<>(ServiceStateCode.SUCCESS,viewPath);
    }


    @Transactional
    @Override
    public ServiceReturn<Boolean> deleteDescribePicture(Merchant merchant, long goodsId, String describePictureName) {
        //图片的保存目录
        String saveDir = Merchant.RESOURCE_ROOT_DIR + merchant.getMerchantAccount() + Merchant.GOODS_DIR + goodsId + File.separator;
        String deleteFilePath = saveDir+describePictureName;
        QueryWrapper<GoodsDescriptionPicture> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id",goodsId);
        queryWrapper.eq("goods_description_picture",deleteFilePath);
        int deleteRow = descriptionPictureMapper.delete(queryWrapper);
        if(deleteRow!=0){
            CachedThreadPoolUtil.submit(()->{
                //异步删除
                try {
                    FileOptionUtil.deleteFile(deleteFilePath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //异步同步到es中
                String script =
                        "if(ctx._source['goodsDescriptionPicture'] != null){" +
                            "def list = ctx._source['goodsDescriptionPicture'];" +
                            "for(int i=0;i<list.length;i++){" +
                                "if(list[i]==params.deleteDescribePicture){" +
                                    "ctx._source['goodsDescriptionPicture'].remove(i);" +
                                    "break;" +
                                "}" +
                            "}" +
                        "}";
                HashMap<String, Object> params = new HashMap<>();
                params.put("deleteDescribePicture",ResponseResult.toRequestPath(deleteFilePath));
                GoodsDetailBrowseInfo detailBrowseInfo = new GoodsDetailBrowseInfo(goodsId);
                //如果不存在该文档记录，则会报错，但是这个错误是可以接收的
                esClient.updateDocument(detailBrowseInfo,script,params);
            });
            return new ServiceReturn<>(ServiceStateCode.SUCCESS,true);
        }
        return new ServiceReturn<>(ServiceStateCode.NO_SUCH_RECORD,false);
    }



    @Transactional
    @Override
    public ServiceReturn<Boolean> deleteDetailPicture(Merchant merchant, long goodsId, String detailPictureName) {
        //图片的保存目录
        String saveDir = Merchant.RESOURCE_ROOT_DIR + merchant.getMerchantAccount() + Merchant.GOODS_DIR + goodsId + File.separator;
        String deleteFilePath = saveDir+detailPictureName;
        QueryWrapper<GoodsDetailsPicture> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id",goodsId);
        queryWrapper.eq("goods_details_picture",deleteFilePath);
        int deleteRow = detailsPictureMapper.delete(queryWrapper);
        if(deleteRow!=0){
            CachedThreadPoolUtil.submit(()->{
                //异步删除
                try {
                    FileOptionUtil.deleteFile(deleteFilePath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //异步同步到es中
                String script =
                        "if(ctx._source['goodsDetailsPicture'] != null){" +
                            "def list = ctx._source['goodsDetailsPicture'];" +
                            "for(int i=0;i<list.length;i++){" +
                                "if(list[i]==params.deleteDetailPicture){" +
                                    "ctx._source['goodsDetailsPicture'].remove(i);" +
                                    "break;" +
                                "}" +
                            "}" +
                        "}";
                HashMap<String, Object> params = new HashMap<>();
                params.put("deleteDetailPicture",ResponseResult.toRequestPath(deleteFilePath));
                GoodsDetailBrowseInfo detailBrowseInfo = new GoodsDetailBrowseInfo(goodsId);
                //如果不存在该文档记录，则会报错，但是这个错误是可以接收的
                esClient.updateDocument(detailBrowseInfo,script,params);
            });
            return new ServiceReturn<>(ServiceStateCode.SUCCESS,true);
        }
        return new ServiceReturn<>(ServiceStateCode.NO_SUCH_RECORD,false);
    }
}
